package com.example.musicplayer.fragment

import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.GridView
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.example.musicplayer.R
import com.example.musicplayer.adapter.BannerAdapter
import com.example.musicplayer.adapter.RecommendMusicAdapter
import com.example.musicplayer.model.Banner
import com.example.musicplayer.model.RecommendMusic

/**
 * 推荐音乐视图
 */
class MusicRecommendationFragment(
    private val bannerList: List<Banner>,
    private val recommendMusicList: List<RecommendMusic>
) : Fragment() {

    private lateinit var viewPager2: ViewPager2
    private val handler = Handler()
    private val runnable = object : Runnable {
        override fun run() {
            val current = viewPager2.currentItem
            val total = bannerList.size
            val next = (current + 1) % total
            viewPager2.setCurrentItem(next, true)
            handler.postDelayed(this, 3000)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val rootView = inflater.inflate(R.layout.fragment_music_recommendation, container, false)

        viewPager2 = rootView.findViewById(R.id.view_pager_banner)
        val bannerAdapter = BannerAdapter(bannerList)
        viewPager2.adapter = bannerAdapter

        viewPager2.offscreenPageLimit = if (bannerList.isNotEmpty()) bannerList.size else 1
        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {})

        handler.postDelayed(runnable, 3000)

        val gridView: GridView = rootView.findViewById(R.id.gridView)
        val recommendMusicAdapter = RecommendMusicAdapter(
            requireContext(),
            recommendMusicList,
            object : RecommendMusicAdapter.OnItemClickListener {
                override fun onItemClick(recommendMusic: RecommendMusic?) {
                    recommendMusic?.let {
                    }
                }
            })
        gridView.adapter = recommendMusicAdapter

        return rootView
    }

    override fun onDestroyView() {
        super.onDestroyView()
        handler.removeCallbacks(runnable)
    }
}